const Service = require("egg").Service;
const errorLog = require("../utils/errorLog");

class RoleMenuService extends Service {
  async addRoleMenu(roleId, roleMenuArr) {
    try {
      await this.app.model.RoleMenu.destroy({
        where: { roleId: roleId },
      });
      const newArr = [];
      roleMenuArr.map((item) => {
        newArr.push({
          roleId: roleId,
          menuId: item,
        });
      });
      return await this.app.model.RoleMenu.bulkCreate(newArr);
    } catch (err) {
      errorLog("RoleMenuService----->createRoleMenu", err);
      return false;
    }
  }

  async updateRoleById(roleData) {
    try {
      const result = await this.app.model.RoleMenu.update(
        { id: roleData.id },
        { where: { id: roleData.id } }
      );
      return result > 0;
    } catch (err) {
      errorLog("RoleMenuService----->updateRoleById", err);
      return false;
    }
  }

  async updateRoleMenu(roleId, roleMenuArr) {
    try {
      await this.app.model.RoleMenu.destroy({
        where: { roleId: roleId },
      });
      const newArr = [];
      roleMenuArr.map((item) => {
        newArr.push({
          roleId: roleId,
          menuId: item,
        });
      });
      return await this.app.model.RoleMenu.bulkCreate(newArr);
    } catch (err) {
      errorLog("RoleMenuService----->updateRoleMenu", err);
      return false;
    }
  }

  async deleteRoleMenu(roleId, options = {}) {
    try {
      const { transaction } = options;
      const result = await this.app.model.RoleMenu.destroy({
        where: { roleId },
        transaction,
      });
      return result > 0;
    } catch (err) {
      errorLog("RoleMenuService----->deleteRoleMenu", err);
      return false;
    }
  }

  async getRoleMenuByRoleId(roleId) {
    try {
      const result = await this.app.model.RoleMenu.findAll({
        where: { roleId },
      });
      return result;
    } catch (err) {
      errorLog("RoleMenuService----->getRoleMenuByRoleId", err);
      return false;
    }
  }
}

module.exports = RoleMenuService;
